package top.gytf.unifiedcall.support.springcloud.producer;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.discovery.event.InstancePreRegisteredEvent;
import org.springframework.context.ApplicationListener;
import top.gytf.unifiedcall.common.detial.UnifiedCallPackageManager;
import top.gytf.unifiedcall.model.detail.UnifiedCallPackageDetail;

import java.util.Map;

/**
 * 处理服务实例注册到注册中心的元数据
 * <p>将服务Producer启用实现的包明细信息放入元数据的指定键
 */
@Slf4j
@RequiredArgsConstructor
public class ServiceInstanceMetadataHandler implements ApplicationListener<InstancePreRegisteredEvent> {
    /**
     * @see UnifiedCallPackageDetail#getName()
     */
    private final String enabledPackage;
    private final UnifiedCallPackageManager unifiedCallPackageManager;

    @Override
    @SneakyThrows
    public void onApplicationEvent(InstancePreRegisteredEvent event) {
        unifiedCallPackageManager.findByName(enabledPackage)
                .ifPresent(detail -> {
                    String value = JSONUtil.toJsonStr(Map.of(
                            "version", detail.getVersion().toString()
                    ));
                    log.debug("新增ServiceInstance元数据：{}", value);
                    event.getRegistration().getMetadata().put("unified-call", value);
                });
    }
}
